<script setup>
import { computed, ref } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh } from "@element-plus/icons-vue";

import { getNetwork, updateNetwork, getWifi, connectWifi, rescanWifi } from "@/api/network";

const editableConnectionName = ref()
const networks = ref([])

function toGetNetwork() {
  getNetwork().then(res => {
    if (res.code === 200) {
      networks.value = res.data
      if (res.data.length && res.data.length > 0) {
        editableConnectionName.value = res.data[0].name
      }
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("网络异常，请稍后重试")
  })
}
toGetNetwork()

function toUpdateNetwork(data) {
  ElMessageBox.confirm("确定要修改WiFi状态吗？", "警告", {
    type: "warning",
  }).then(() => {
    updateNetwork(data).then(res => {
      if (res.code === 200) {
        ElMessage.success("修改成功")
        toGetNetwork()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error("网络异常，请稍后重试")
    })
  }).catch(() => {})
}

// 查看wifi
const wifiLoading = ref(false)
const wifiList = ref([])
const __usedWifi = ref()
const usedWifi = computed({
  get: () => __usedWifi.value,
  set: (ssid) => {
    ElMessageBox.prompt("请输入WiFi密码", "提示", {
      confirmButtonText: "连接",
      showCancelButton: false,
      inputType: "password"
    }).then(({ value }) => {
      wifiLoading.value = true
      connectWifi({ssid, password: value}).then(res => {
        if (res.code === 200) {
          ElMessage.success("连接成功")
          toGetWifi(() => wifiLoading.value = false)
          toGetNetwork()
        } else {
          ElMessage.error(res.msg)
          wifiLoading.value = false
        }
      }).catch(err => {
        console.log(err)
        ElMessage.error("网络异常，请稍后重试")
        wifiLoading.value = false
      })
    })
  }
})

function toGetWifi(success = () => {}) {
  getWifi().then(res => {
    if (res.code === 200) {
      wifiList.value = res.data
      for (let i = 0; i < wifiList.value.length; i++) {
        const item = wifiList.value[i];
        if (item.used) {
          __usedWifi.value = item.ssid
          continue
        }
      }
      success()
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("网络异常，请稍后重试")
  })
}
toGetWifi() 

function wifiDisplayChange(visible) {
  if (visible) toGetWifi()
}

function signalGraph(number) {
  if (number < 33.3) {
    return "▁▁▁"
  } else if (number < 66.6) {
    return "▁▃▁"
  } else {
    return "▁▃▆"
  }
}
function wifiChange(value) {
  console.log(value);
}

const rescanning = ref(false)
function toRescanWifi() {
  rescanning.value = true
  rescanWifi().then(res => {
    if (res.code === 200) {
      toGetWifi(() => {
        rescanning.value = false
        ElMessage.success("WiFi列表更新成功")
      })
    } else {
      ElMessage.error("出现异常，wifi数据获取失败")
      rescanning.value = false
    }
  }).catch(err => {
    console.log(err);
    ElMessage.error("网络异常，请稍后重试")
    rescanning.value = false
  })
}
</script>

<template>
  <el-tabs
    type="border-card" v-model="editableConnectionName"
  >
    <el-tab-pane
      v-for="item in networks"
      :key="item.name"
      :name="item.name"
    >
      <template #label>
        <span style="margin-right: 8px;">
          {{ item.type === 'wifi' ? `WiFi (${item.name})` : item.device }}
        </span>
        <el-tag v-if="item.state === 'connected'" type="success">已连接</el-tag>
        <el-tag v-else-if="item.state === 'disconnected'" type="error">断开连接</el-tag>
        <el-tag v-else-if="item.state === 'unavailable'" type="info">无效</el-tag>
      </template>
      <el-form label-width="84px">
        <el-form-item label="启用编辑">
          <el-switch v-model="item.editable" />
        </el-form-item>
        <el-form-item v-if="item.type == 'wifi'" label="选择WiFi">
          <el-select 
            :disabled="!item.editable" 
            v-loading="wifiLoading"
            v-model="usedWifi" 
            @visible-change="wifiDisplayChange"
            @change="wifiChange"
          >
            <el-option v-for="wifi in wifiList" 
              :label="`${signalGraph(wifi.signal)} ${wifi.ssid}`" 
              :value="wifi.ssid"
            />
          </el-select>
          <el-button 
            style="margin-left: 4px;" 
            :disabled="rescanning || (!item.editable)" 
            :icon="Refresh" 
            circle link type="primary"
            @click="toRescanWifi" 
          />
        </el-form-item>
        <el-form-item label="工作模式">
          <el-switch
            :disabled="!item.editable"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #409eff"
            v-model="item.method"
            inactive-text="静态"
            active-text="动态"
            inactive-value="manual"
            active-value="auto"
          />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input :readonly="!item.editable || item.method === 'auto'" v-model="item.address" />
        </el-form-item>
        <el-form-item label="子网掩码">
          <el-input :readonly="!item.editable || item.method === 'auto'" v-model="item.netmask" />
        </el-form-item>
        <el-form-item label="网关地址">
          <el-input :readonly="!item.editable || item.method === 'auto'" v-model="item.gateway" />
        </el-form-item>
        <el-form-item label="DNS">
          <el-input :readonly="!item.editable || item.method === 'auto'" v-model="item.dns" />
        </el-form-item>
        <el-form-item v-if="item.editable">
          <el-button type="primary" @click="toUpdateNetwork(item)">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>
</template>

<style lang="scss" scoped>
</style>